package com.example.myapplication.camera1

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.hardware.Camera
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.myapplication.R
import com.example.myapplication.camera1.camrea.CameraHelper
import com.example.myapplication.camera1.camrea.OnCaptureCallback
import com.example.myapplication.camera1.view.MaskSurfaceView
import com.media.photocamera.utils.CameraConstans
import com.media.photocamera.utils.CameraFileUtils
import com.media.photocamera.utils.CameraUiUtil
import java.io.File

class TakeFacePhotoActivity : Activity(), OnCaptureCallback {
    private val STORAGE_REQUEST_CODE = 0
    private val CAMREA = 111

    private var surfaceview: MaskSurfaceView? = null

    private var imageView: ImageView? = null

    //	拍照
    private var btn_capture: ImageView? = null

    //	重拍
    private var btn_recapture: ImageView? = null

    //	取消
    private var btn_cancel: TextView? = null

    //	确认
    private var btn_ok: ImageView? = null

    //切换摄像头
    private var btn_change: ImageView? = null

    //开灯
    private var btn_night: ImageButton? = null

    //	拍照后得到的保存的文件路径
    private var filepath: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        val lp = window.attributes
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }
        window.attributes = lp
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN)
        CameraUiUtil.transparencyBar(this)
        requestPermission()
        this.setContentView(R.layout.activity_facephoto)
        surfaceview = findViewById<View>(R.id.surface_view) as MaskSurfaceView
        imageView = findViewById<View>(R.id.image_view) as ImageView
        btn_capture = findViewById<View>(R.id.btn_capture) as ImageView
        btn_recapture = findViewById<View>(R.id.btn_recapture) as ImageView
        btn_ok = findViewById<View>(R.id.btn_ok) as ImageView
        btn_cancel = findViewById<View>(R.id.btn_cancel) as TextView
        btn_change = findViewById<View>(R.id.btn_change) as ImageView
        btn_night = findViewById<View>(R.id.btn_night) as ImageButton
        var scale = intent.getDoubleExtra(CameraConstans.FACEPHOTO_scale, 0.75)
        var widthScale = intent.getDoubleExtra(CameraConstans.FACEPHOTO_widthScale, 0.8)
//        var light = intent.getIntExtra(Constans.FACEPHOTO_light, 1)
        var isSaveToAlbum = intent.getIntExtra(CameraConstans.FACEPHOTO_isSaveToAlbum, 0)
        var isFront = intent.getIntExtra(CameraConstans.FACEPHOTO_isFront, 0)
        var limit = intent.getIntExtra(CameraConstans.FACEPHOTO_limit, 1024)
        CameraHelper.getInstance().setLimit(limit)
        if (isFront == 1) {
            CameraHelper.getInstance().setFrontCamera(true)
            //前置摄像头
            btn_night?.visibility = View.GONE
        } else {
            CameraHelper.getInstance().setFrontCamera(false)
            //后置摄像头
            btn_night?.visibility = View.VISIBLE
        }
        CameraHelper.getInstance().setPicQuality(100)
        val targetWidth: Double = CameraUiUtil.getScreamWidth(this) * widthScale
        if (scale < 0.6) {
            scale = 0.6
        }
        val targetHight = (targetWidth / scale!!).toInt()
        // 设置矩形区域大小
        surfaceview?.setMaskSize(targetWidth.toInt(), targetHight)
        setButtomControlStatus(1)
        //拍照
        btn_capture?.setOnClickListener {
            setButtomControlStatus(2)
            CameraHelper.getInstance().tackPicture(application,this@TakeFacePhotoActivity)
        }

        //重拍
        btn_recapture?.setOnClickListener {
            setButtomControlStatus(1)
            imageView!!.visibility = View.GONE
            surfaceview?.setVisibility(View.VISIBLE)
            deleteFile()
            CameraHelper.getInstance().startPreview()
        }
        //切换摄像头
        btn_change?.setOnClickListener {
            it.isEnabled = false
            CameraHelper.getInstance().changeCamera()
            val changeCamera = CameraHelper.getInstance().isFrontCameara()
            if (changeCamera) {
                //前置摄像头
                btn_night?.visibility = View.GONE
            } else {
                //后置摄像头
                btn_night?.visibility = View.VISIBLE
            }
            it.postDelayed(Runnable { it.isEnabled = true }, 1000)
        }
        surfaceview?.setOnClickListener {
            CameraHelper.getInstance().autoFocus(null)
        }

        //确认
        btn_ok?.setOnClickListener {
            setResult(RESULT_OK, Intent().putExtra(CameraConstans.CALL_BACK_FACEPHOTO_CODE, filepath))
            finish()
            if (isSaveToAlbum == 1) {
                CameraFileUtils.copyFile2Album(this.application, filepath, CameraConstans.IMAGEPATH)
            }
        }

        //取消
        btn_cancel?.setOnClickListener {
            deleteFile()
            finish()
        }
        //灯光
        btn_night?.setOnClickListener {
            var status = CameraHelper.getInstance().flashlightStatus
            var flashlightStatus: String = when (status) {
                Camera.Parameters.FLASH_MODE_OFF -> {
                    btn_night?.setImageResource(R.drawable.camerax_flash_on)
                    Camera.Parameters.FLASH_MODE_ON
                }
                Camera.Parameters.FLASH_MODE_ON -> {
                    try {
                        val supportedModes: List<String> =
                                CameraHelper.getInstance().camera.getParameters().getSupportedFlashModes()
                        if (supportedModes.contains(Camera.Parameters.FLASH_MODE_AUTO)) {
                            btn_night?.setImageResource(R.drawable.camerax_flash_auto)
                            Camera.Parameters.FLASH_MODE_AUTO
                        } else {
                            btn_night?.setImageResource(R.drawable.camerax_flash_off)

                            Camera.Parameters.FLASH_MODE_OFF
                        }
                    } catch (e: Exception) {
                        Camera.Parameters.FLASH_MODE_OFF
                    }
                }
                Camera.Parameters.FLASH_MODE_AUTO -> {
                    btn_night?.setImageResource(R.drawable.camerax_flash_off)
                    Camera.Parameters.FLASH_MODE_OFF
                }
                else -> {
                    btn_night?.setImageResource(R.drawable.camerax_flash_off)
                    Camera.Parameters.FLASH_MODE_OFF
                }
            }
            CameraHelper.getInstance().setFlashMode(flashlightStatus)
        }
        //设置屏幕亮度最大
        window.attributes.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL;
        CameraHelper.getInstance().setPictureSaveDictionaryPath(this.cacheDir.absolutePath)
    }

    /**
     * 设置按钮状态
     */
    private fun setButtomControlStatus(isCapture: Int) {
        if (isCapture == 1) {
            //正在拍照
            btn_cancel!!.visibility = View.VISIBLE
            btn_capture!!.visibility = View.VISIBLE
            btn_ok!!.visibility = View.GONE
            btn_recapture!!.visibility = View.GONE
            if (CameraHelper.getInstance().isFrontCameara) {
                btn_night?.visibility = View.GONE
            } else {
                btn_night?.visibility = View.VISIBLE
            }
            btn_change?.visibility = View.VISIBLE
        } else if (isCapture == 0) {
            //拍照成功
            btn_cancel!!.visibility = View.GONE
            btn_capture!!.visibility = View.GONE
            btn_ok!!.visibility = View.VISIBLE
            btn_recapture!!.visibility = View.VISIBLE
            btn_night?.visibility = View.GONE
            btn_change?.visibility = View.GONE
        } else if (isCapture == 2) {
            //拍照等待 裁剪回调
            btn_cancel!!.visibility = View.GONE
            btn_capture!!.visibility = View.GONE
            btn_ok!!.visibility = View.GONE
            btn_recapture!!.visibility = View.GONE
            btn_night?.visibility = View.GONE
            btn_change?.visibility = View.GONE
        }
    }


    /**
     * 删除图片文件呢
     */
    private fun deleteFile() {
        if (TextUtils.isEmpty(filepath)) {
            return
        }
        val f = File(filepath)
        if (f.exists()) {
            f.delete()
        }
    }

    override fun onCapture(success: Boolean, filepath: String?) {
        runOnUiThread {
            this.filepath = filepath
//            var message = "拍照成功"
            if (!success) {
//                message = "拍照失败"
                CameraHelper.getInstance().startPreview()
                imageView!!.visibility = View.GONE
                surfaceview?.setVisibility(View.VISIBLE)
                setButtomControlStatus(1)
            } else {
                imageView!!.visibility = View.VISIBLE
                surfaceview?.setVisibility(View.GONE)
                imageView!!.setImageBitmap(BitmapFactory.decodeFile(filepath))
                setButtomControlStatus(0)
            }
//            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        }
    }


    //请求视频和存储权限
    private fun requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                !== PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_REQUEST_CODE)
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                !== PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMREA)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == STORAGE_REQUEST_CODE || requestCode == CAMREA) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                finish()
                Toast.makeText(this, "需要开启相机和存储权限", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onDestroy() {
        //设置屏幕亮度正常
        window.attributes.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE
        super.onDestroy()
        CameraHelper.getInstance().releaseCamera()
    }

}
